<?php
/*****************************************************************
 * Fusion.Board
 *
 * @author                Denis Wrobel
 * @license               http://www.gnu.org/licenses/gpl-3.0.html
 * @version               0.1
 *
 *****************************************************************/

if( !defined( 'IN_SCRIPT' ) )
{
    die( 'Go Away!' );
}

class Core
{
    public function _GET( $index, $trim = 0 )
    {
        if( isset( $_GET[ $index ] ) )
        {
            if( $trim )
            {
                $_GET[ $index ] = trim( $_GET[ $index ] );
            }
            
            return addslashes( $_GET[ $index ] );
        }
        else
        {
            return NULL;
        }
    }
    
    public function _POST( $index, $trim = 0 )
    {
        if( isset( $_POST[ $index ] ) )
        {
            if( $trim )
            {
                $_POST[ $index ] = trim( $_POST[ $index ] );
            }
            
            return addslashes( $_POST[ $index ] );
        }
        else
        {
            return false;
        }
    }
    
    /*
     * Remove slashes and trim
     * @param string $item
     */
    public function filterItem( $item )
    {
        return stripslashes( trim( $item ) );
    }
    
    public function htmlFilter( $item )
    {
        return htmlspecialchars( stripslashes( trim( $item ) ) );
    }
    
    /*
     * Create new cookie
     * @param string $name Cookie name
     * @param string $value Cookie content
     */
    public function createCookie( $name, $value, $lifetime = 3600 )
    {
        global $board;
        
        $life = time() + $lifetime;
        
        setcookie( $board['cookie_prefix'] . $name, urlencode( $value ), $life );
    }
    
    /*
     * Return cookie data
     * @param string $cookie_name
     */
    public function cookieData( $cookie_name = '' )
    {
        global $board;
        
        return ( isset( $_COOKIE[ $board['cookie_prefix'] . $cookie_name ] ) ) ? urldecode( $_COOKIE[ $board['cookie_prefix'] . $cookie_name ] ) : false;
    }
    
    /*
     * Kill cookie
     * @param string $name
     */
    public function destroyCookie( $name )
    {
        setcookie( $board['cookie_prefix'] . $name, '', ( time() - 3600 ) );
    }
    
    /*
     * Return forum stats
     */
    public function boardStats( $record )
    {
        global $db;
        
        $query = $db->query( 'SELECT *
                              FROM ' . TABLE_PREFIX . 'stats' );
        
        $stats = $db->fetch( $query );
        
        if( $record > $stats['most_users_online'] )
        {
            $db->query( 'UPDATE ' . TABLE_PREFIX . 'stats
                         SET most_users_online = ' . $record . ',
                         most_users_date = \'' . time() . '\'' );
        }
    
        return $stats;
    }
    
    public function usersOnline()
    {
        global $board, $db;
        
        $online = array();
        $online['guests'] = 0;
        $online['users_count'] = 0;
        $online['all'] = 0;
        $online['users'] = array();
        
        $query = $db->query( 'SELECT s.*, u.user_id, u.username, g.group_id, g.group_name, g.group_style
                              FROM ' . TABLE_PREFIX . 'sessions s
                              LEFT JOIN ' . TABLE_PREFIX . 'users u
                              ON u.user_id = s.session_user
                              LEFT JOIN ' . TABLE_PREFIX . 'groups g
                              ON g.group_id = u.user_maingroup
                              WHERE s.session_lasttime > \'' . ( time() - ( $board['stat_time'] * 60 ) ) . '\'' );
        
        while( $row = $db->fetch( $query ) )
        {
            if( $row['session_logged'] )
            {
                $online['all']++;
                $online['users_count']++;
                $online['users'][] = $row;
            }
            else
            {
                $online['all']++;
                $online['guests']++;
            }
        }
        
        return $online;
    }
    
    public function formatTimeStamp( $timestamp = 0 )
    {
        global $language;
        
        if( !$timestamp )
        {
            return $timestamp;
        }
        else
        {
            $convert = getdate( $timestamp );
            
            $convert['minutes'] = ( $convert['minutes'] < 10 ) ? 0 . $convert['minutes'] : $convert['minutes'];
            
            if( date( 'jnY' ) == $convert['mday'] . $convert['mon'] . $convert['year'] )
            {
                if( date( 'g' ) == $convert['hours'] )
                {
                    if( ( date( 'i' ) - 1 ) < $convert['minutes'] )
                    {
                        return $language->string( 'moment_ago' );
                    }
                    else
                    {
                        return $language->string( 'today' ) . ' ' . $convert['hours'] . ':' . $convert['minutes'];
                    }
                }
                else
                {
                    return $language->string( 'today' ) . ' ' . $convert['hours'] . ':' . $convert['minutes'];
                }
            }
            else
            {
                return $convert['mday'] . ' ' . $language->months[ $convert['mon'] ] . ' ' . $convert['year'] . ', ' . $convert['hours'] . ':' . $convert['minutes'];
            }
        }
    }
    
    public function daysAgoTimeStamp( $timestamp )
    {
        $time = time() - $timestamp;
        
        $days = round( $time / 86400 );
        return $days;
    }
    
    /*
     * Cut string
     * @param string $string String
     * @param int $limit Chars limit
     * @param int $three_dots Finish string with '...' 
     */
    public function cutString( $string, $limit = 0, $three_dots = 0 )
    {
        if( $limit == 0 )
        {
            $limit = strlen( $string );
        }
        
        return ( $three_dots ) ? substr( $string, 0, $limit ) . '...' : substr( $string, 0, $limit );
    }
    
    
    /*
     * Check if $email is Email
     * @param string $email Email
     */
    public function isEmail( $email )
    {
        if( preg_match( '/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i', $email ) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    /*
     * Check if $username is valid username
     * @param string $username Username
     */
    public function isUsername( $username )
    {
        preg_match( '/([a-zA-Z0-9_]{0,100})/', $username, $check );
        if( $check[0] == $username )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    /*
     * Check if $username is available
     * @param string $username
     */
    public function isUsernameInUse( $username )
    {
        global $db;
        
        $query = $db->query( 'SELECT username
                              FROM ' . TABLE_PREFIX . 'users
                              WHERE lower(username) = \'' . strtolower( $username ) . '\'' );
        
        $fetch = $db->fetch( $query );
        
        return $fetch['username'];
    }
    
    /*
     * Check if $email is available
     * @param string $email Email
     */
    public function isEmailInUse( $email )
    {
        global $db;
        
        $query = $db->query( 'SELECT user_email
                              FROM ' . TABLE_PREFIX . 'users
                              WHERE lower(user_email) = \'' . strtolower( $email ) . '\'' );
        
        $fetch = $db->fetch( $query );
        
        return $fetch['user_email'];
    }
    
    
    /*
     * Return extra fields
     * @param string $location Extra field access location
     */
    public function getExtraFields( $location = '' )
    {
        global $db;
        
        if( strlen( $location ) )
        {
            $query = $db->query( 'SELECT *
                                  FROM ' . TABLE_PREFIX . 'extra_fields
                                  WHERE ' . $location . ' = 1' );
        }
        else
        {
            $query = $db->query( 'SELECT *
                                  FROM ' . TABLE_PREFIX . 'extra_fields' );
        }
        
        $fields = array();
        
        while( $row = $db->fetch( $query ) )
        {
            $fields[] = $row;
        }
        
        return $fields;
    }
    
    /*
     * Return extra fields and their data for user
     * @param integer $user_id User id
     * @param string $location Extra field access location
     */
    public function userExtraFields( $user_id = 0, $location = '' )
    {
        global $db;
        
        if( strlen( $location ) )
        {
            $query = $db->query( 'SELECT e.*, d.*
                                  FROM ' . TABLE_PREFIX . 'extra_fields e
                                  LEFT JOIN ' . TABLE_PREFIX . 'extra_fields_data d
                                  ON d.field_user = \'' . $user_id . '\'
                                  AND d.parent_field = e.field_id
                                  WHERE e.' . $location . ' = 1' );
        }
        else
        {
            $query = $db->query( 'SELECT e.*, d.*
                                  FROM ' . TABLE_PREFIX . 'extra_fields e
                                  LEFT JOIN ' . TABLE_PREFIX . 'extra_fields_data d
                                  ON d.field_user = \'' . $user_id . '\'
                                  AND d.parent_field = e.field_id' );
        }
        
        $fields = array();
        
        while( $row = $db->fetch( $query ) )
        {
            $fields[] = $row;
        }
        
        return $fields;
    }
    
    /*
     * Replace {USERNAME} from $style with $username
     * @param string $style Style
     * @param string $username Replacer
     */
    public function colorUsername( $style, $username )
    {
        if( $style )
        {
            return str_replace( '{USERNAME}', $username, $style );
        }
        else
        {
            return $username;
        }
    }
    
    /*
     * AntiFlood in comments
     * @param integer $user_id User id
     */
    public function checkCommentsFlood( $user_id, $flood_time = 60 )
    {
        global $db, $session;
        
        $query = $db->query( 'SELECT comment_id, comment_author, comment_date
                              FROM ' . TABLE_PREFIX . 'comments
                              WHERE comment_author = \'' . $user_id . '\'
                              ORDER BY comment_id DESC
                              LIMIT 1' );
        
        $flood = $db->fetch( $query );
        
        if( $flood )
        {
            if( $flood['comment_date'] > ( time() - $flood_time ) && $session['group_level'] != 'ADMIN' )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    
    public function pagination( $elements, $perPage = 15, $onPage, $url )
    {
        global $language;
        
        $pages = ceil( $elements / $perPage );
        
        $i = 1;
        $pagination = '<span class="pagination">';
        
        if( $pages >= 5 )
        {
            while( $i <= $pages )
            {
                $urll = str_replace( '{PAGE}', $i, $url );
                
                if( $i == 1 )
                {
                    $pagination .= '<a href="' . $urll . '">' . $language->string( 'first_page' ) . '</a>, ';
                }
                elseif( $i == $pages )
                {
                    $pagination .= '<a href="' . $urll . '">' . $language->string( 'last_page' ) . '</a>, ';
                }
                elseif( $i > ( $onPage - 4 ) && $i < ( $onPage + 4 ) && $i > 1 && $i < $pages && $i != $onPage )
                {
                    if( $i < $pages )
                    {
                        $pagination .= '<a href="' . $urll . '">' . $i . '</a>, ';
                    }
                }
                
                if( $i == $onPage && $i != $pages )
                {
                    $pagination .= '<a class="actualPage">' . $i . '</a>, ';
                }
                
                $i++;
            }
        }
        else
        {
            while( $i <= $pages )
            {
                if( $i == $onPage )
                {
                    $pagination .= '<a class="actualPage">' . $i . '</a>, ';
                    
                    $i++;
                }
                else
                {
                    $urll = str_replace( '{PAGE}', $i, $url );
                    
                    $pagination .= '<a href="' . $urll . '">' . $i . '</a>, ';
                    
                    $i++;
                }
            }
        }
        
        $pagination = substr( $pagination, 0, strlen( $pagination ) - 2 );
        
        $pagination .= '</span>';
        
        return $pagination;
    }
}

?>